'use strict';

var express = require('express');
var router = express.Router();

var $file = require('../midware/file');
var $course = require('../midware/admin/course');
var $session = require('../midware/session');

let v = (v, def)=>v === undefined ? def : v;

//获取列表
router.get('/list', function (req, res, next) {

    let cookies = req.cookies;
    let ssid = cookies.ssid;

    new Promise((O, X)=> {
        O();
    })
        .then(()=> {
            $session.isAdmin(ssid);
            return $course.getAll();
        })
        .then((courses)=> {
            res.json({
                code: 0,
                list: courses
            });
        })
        .catch((e)=> {
            res.json({
                code: e.code,
                msg: e.msg
            });
        });
});

//获取某一课件详情
router.get('/', function (req, res, next) {

    let _id = req.query._id;

    $course
        .getOnebyId(_id)
        .then((course)=> {
            res.json({
                code: 0,
                info: course
            });
        });
});

//新建课件
router.post('/', function (req, res, next) {

    try {

        let cookies = req.cookies;
        let ssid = cookies.ssid;

        let data = JSON.parse(req.body.json);

        let _class = v(data.class),
            title = v(data.title),
            tags = v(data.tags || ''),
            article = v(data.article, ''),
            imgs = v(data.imgs, []),
            attachments = v(data.attachments, []);

        new Promise((O, X)=> {
            O();
        })
            .then(()=> {
                $session.isAdmin(ssid);

                if (!_class || !_class.length || _class.length == 0) {
                    throw {
                        code: 9999,
                        msg: '没有选择班级'
                    };
                }
                if (!title || !title.length || title.length == 0) {
                    throw {
                        code: 9999,
                        msg: '没有标题'
                    };
                }

                let uploadQueue = [].concat(imgs, attachments);

                return Promise.all(uploadQueue.map((file)=> {

                    return $file.updatedByPath(file.path, {
                        name: file.name,
                        use: true
                    })

                }));
            })
            .then(()=> {
                return $course.save({
                    class: _class,
                    title: title,
                    tags: tags,
                    article: article,
                    imgs: imgs,
                    attachments: attachments
                })
            })
            .then(()=> {
                res.json({
                    code: 0
                });
            })
            .catch((e)=> {
                let uploadQueue = [].concat(imgs, attachments);

                Promise.all(uploadQueue.map((file)=> {

                    return $file.deleteByPath(file.path)

                })).then(()=> {

                    res.json({
                        code: e.code,
                        msg: e.msg
                    });

                });
            });

    } catch (e) {
        res.json({
            code: 9999,
            msg: '接口发生错误'
        });
    }

});

//编辑课件
router.put('/', function (req, res, next) {

    try {

        let cookies = req.cookies;
        let ssid = cookies.ssid;

        let data = JSON.parse(req.body.json);

        let id = v(data._id),
            _class = v(data.class),
            title = v(data.title),
            tags = v(data.tags || ''),
            article = v(data.article, ''),
            imgs = v(data.imgs, []),
            attachments = v(data.attachments, []);

        new Promise((O, X)=> {
            O();
        })
            .then(()=> {
                $session.isAdmin(ssid);

                if (!_class || !_class.length || _class.length == 0) {
                    throw {
                        code: 9999,
                        msg: '没有选择班级'
                    };
                }
                if (!title || !title.length || title.length == 0) {
                    throw {
                        code: 9999,
                        msg: '没有标题'
                    };
                }

                return $course.getOnebyId(id);
            })
            .then((course)=> {

                let newList = [].concat(imgs, attachments).map((nf)=> {
                    nf.handle = 'edit';
                    return nf;
                });
                let oldList = [].concat(course.imgs, course.attachments).map((of)=> {
                    of.handle = 'delete';
                    return of;
                });

                newList.map((nf)=> {
                    if (!oldList.some((of,i)=> {
                            if (of.path == nf.path) {
                                oldList[i] = nf;
                                return true;
                            }
                        })) {
                        oldList.push(nf);
                    }
                });
                console.log(oldList);
                return Promise.all(oldList.map((file)=> {

                    if (file.handle == 'delete') {
                        return $file.deleteByPath(file.path)
                    } else {
                        return $file.updatedByPath(file.path, {
                            name: file.name,
                            use: true
                        })
                    }

                }));
            })
            .then(()=> {
                return $course.update(id, {
                    class: _class,
                    title: title,
                    tags: tags,
                    article: article,
                    imgs: imgs,
                    attachments: attachments
                })
            })
            .then(()=> {
                res.json({
                    code: 0
                });
            })
            .catch((e)=> {
                console.log(e);

                res.json({
                    code: e.code,
                    msg: e.msg
                });

                Promise.all(uploadQueue.map((file)=> {

                    return $file.deleteByPath(file.path)

                })).then(()=> {


                });
            });

    } catch (e) {
        res.json({
            code: 9999,
            msg: '接口发生错误'
        });
    }

});

//编辑课件
router.delete('/', function (req, res, next) {

    try {

        let cookies = req.cookies;
        let ssid = cookies.ssid;

        let id = v(req.body._id);

        new Promise((O, X)=> {
            O();
        })
            .then(()=> {
                $session.isAdmin(ssid);

                return $course.getOnebyId(id);
            })
            .then((course)=> {

                let fileList = [].concat(course.imgs, course.attachments);

                return Promise.all(fileList.map((file)=> {
                    return $file.deleteByPath(file.path)
                }));
            })
            .then(()=> {
                return $course.deleteById(id)
            })
            .then(()=> {
                res.json({
                    code: 0
                });
            })
            .catch((e)=> {
                console.log(e);

                res.json({
                    code: e.code,
                    msg: e.msg
                });

            });

    } catch (e) {
        console.log('ERROR:' + e);
        res.json({
            code: 9999,
            msg: '接口发生错误'
        });
    }

});

module.exports = router;